home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / delphi.swg / 0080_Using TStream-TWriter-TReader.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1995-11-24  |  1.9 KB  |  68 lines

  1.  
  2. The following example shows how to write and read data to
  3. and from a file.  It is intended merely as a starting
  4. point for those that are struggling to get started with
  5. file related IO.  Please read the documentation on each
  6. object for more information.  Some very minimal exception
  7. handling is thrown in and by no means constitutes a
  8. robust solution.
  9.  
  10. Best regards,
  11. Michael Vincze
  12. mav@asd470.dseg.ti.com
  13.  
  14. ----------
  15.  
  16. In order to setup the program, place a TMemo component on
  17. a form with a Write captioned and a Read captioned button.
  18. Run the program, place some lines in the "memo", then
  19. press on Write.  Clear the "memo", and press on Read.
  20.  
  21.   procedure TForm1.BtnWriteClick(Sender: TObject);
  22.   { by:  Michael Vincze
  23.   }
  24.   var
  25.     FileStream: TFileStream;
  26.     Writer    : TWriter;
  27.     I         : Integer;
  28.   begin
  29.   FileStream := TFileStream.Create ('c:\delphi\projects\delta40\fileio\stream.txt',
  30.     fmCreate or fmOpenWrite or fmShareDenyNone);
  31.   Writer := TWriter.Create (FileStream, $ff);
  32.   Writer.WriteListBegin;
  33.   for I := 0 to Memo1.Lines.Count - 1 do Writer.WriteString (Memo1.Lines[I]);
  34.   Writer.WriteListEnd;
  35.   Writer.Destroy;
  36.   FileStream.Destroy;
  37.   end;
  38.  
  39.   procedure TForm1.BtnReadClick(Sender: TObject);
  40.   { by:  Michael Vincze
  41.   }
  42.   var
  43.     FileStream: TFileStream;
  44.     Reader    : TReader;
  45.   begin
  46.   { try opening a non existent file
  47.   }
  48.   try
  49.     FileStream := TFileStream.Create ('c:\delphi\projects\delta40\fileio\bogus.txt',
  50.       fmOpenRead);
  51.   except
  52.     ; { no need to Destroy since the Create failed  }
  53.     end;
  54.  
  55.   FileStream := TFileStream.Create ('c:\delphi\projects\delta40\fileio\stream.txt',
  56.     fmOpenRead);
  57.   Reader := TReader.Create (FileStream, $ff);
  58.   Reader.ReadListBegin;
  59.   Memo1.Lines.Clear;
  60.   while not Reader.EndOfList do Memo1.Lines.Add (Reader.ReadString);
  61.   Reader.ReadListEnd;
  62.   Reader.Destroy;
  63.   FileStream.Destroy;
  64.   end;
  65.  
  66.  
  67.  
  68.